const Wechat = require('../util/Wechat')
const logger = require('log4js').getLogger()
const fanliTool = require('../util/fanliTool')
const taobaoLoginResolveMng = require('../mng/taobaoLoginResolveMng')

module.exports = (req, res) => {
    var wechat = Wechat({
        token: 'Je40r3LQIuM4ZGTkJjfcYuSfZa2LdlyH'
    })
    if (req.method === 'GET') {
        wechat.checkSignature(req, res)
    } else {
        wechat.handler(req, res).then(result => {
            //logger.debug('[' + __filename + ':' + __line + ']', result)
            if (result.ToUserName == 'gh_f6b90c571a2e') {
                res.writeHead(200, {
                    'Content-Type': 'text/plain'
                })
                res.end('success')
                switch (result.MsgType) {
                    case 'text':
                        const mongoMng = require('../mng/mongoMng')
                        if (!mongoMng.db) {
                            logger.error('[' + __filename + ':' + __line + '] 未连接mongo')
                            return;
                        }
                        mongoMng.db.collection('user').find({
                            wechat: result.FromUserName
                        }).toArray((err, docs) => {
                            if (err) {
                                logger.error('[' + __filename + ':' + __line + ']', err)
                                return
                            }
                            if (docs.length == 0) {
                                mongoMng.db.collection('user_promoter').find({
                                    wechat: result.FromUserName
                                }).toArray((err, docs) => {
                                    if (err) {
                                        logger.error('[' + __filename + ':' + __line + ']', err)
                                        return
                                    }
                                    let content = '请先绑定旅悠账户，否则返利无法返还到相应账户。https://etourly.com/#/register'
                                    if (docs.length > 0) {
                                        content += '?promoter=' + docs[0].promoter_phone
                                    }
                                    Wechat({
                                        AppID: 'wx226c3c9557c44304',
                                        AppSecret: '8bff6155d050947d06bf7802e69f4acb'
                                    }).messageCustomSend({
                                        touser: result.FromUserName,
                                        msgtype: 'text',
                                        content: content
                                    }).then(result => {
                                        logger.debug('[' + __filename + ':' + __line + ']', result)
                                    }, result => {
                                        logger.error('[' + __filename + ':' + __line + ']', result)
                                    })
                                })
                            } else {
                                logObj = {
                                    wechat: result.FromUserName
                                }
                                var customer_phone = ''
                                if (docs.length > 0) {
                                    logObj.customer_phone = docs[0].phone
                                }
                                getAdvLink(result, logObj).then(() => {}, () => {
                                    appendTaobaoResolvePromise(result, logObj)
                                })
                            }
                        }, result => {
                            logger.debug('[' + __filename + ':' + __line + ']', result)
                        })
                        break
                    case 'event':
                        //logger.debug('[' + __filename + ':' + __line + ']', result)
                        switch (result.Event) {
                            case 'subscribe':
                            case 'SCAN':
                                const mongoMng = require('../mng/mongoMng')
                                if (!mongoMng.db) {
                                    logger.error('[' + __filename + ':' + __line + '] 未连接mongo')
                                    return
                                }
                                mongoMng.db.collection('user').find({
                                    wechat: result.FromUserName
                                }).toArray((err, docs) => {
                                    if (err) {
                                        logger.error('[' + __filename + ':' + __line + ']', err)
                                        resolve()
                                        return
                                    }
                                    if (docs.length > 0) {
                                        return
                                    }
                                    new Promise(resolve => {
                                        if (!result.EventKey) {
                                            resolve()
                                            return
                                        }
                                        logger.debug('[' + __filename + ':' + __line + ']', result.EventKey)
                                        if (result.EventKey.startsWith('qrscene_'))
                                            result.EventKey = result.EventKey.substring('qrscene_'.length)
                                        var sceneId = result.EventKey
                                        mongoMng.db.collection('user').find({
                                            wechatSceneId: parseInt(sceneId)
                                        }).toArray((err, docs) => {
                                            if (err) {
                                                logger.error('[' + __filename + ':' + __line + ']', err)
                                                resolve()
                                                return
                                            }
                                            if (docs.length == 0) {
                                                resolve()
                                                return
                                            }
                                            resolve(docs[0].phone)
                                        })
                                    }).then(_result => {
                                        var content = '购物：点击绑定手机号码，开启省钱购之旅。https://etourly.com/#/register'
                                        if (_result) {
                                            content += '?promoter=' + _result
                                            mongoMng.db.collection('user_promoter').insert({
                                                wechat: result.FromUserName,
                                                promoter_phone: _result
                                            })
                                        }
                                        content += '\r\n\r\n加油：点击底部“能源优惠”按钮👇'
                                        Wechat({
                                            AppID: 'wx226c3c9557c44304',
                                            AppSecret: '8bff6155d050947d06bf7802e69f4acb'
                                        }).messageCustomSend({
                                            touser: result.FromUserName,
                                            msgtype: 'text',
                                            content
                                        }).then(result => {
                                            if (result.errcode)
                                                logger.error('[' + __filename + ':' + __line + ']', JSON.stringify(result))
                                        }, result => {
                                            logger.error('[' + __filename + ':' + __line + ']', result)
                                        })
                                    })
                                })
                                break
                            default:
                                break
                        }
                        break
                    default:
                        wechat.send('success')
                        break
                }
            } else {
                switch (result.MsgType) {
                    case 'event':
                        if (result.Event == 'CLICK') {
                            switch (result.EventKey) {
                                case '10':
                                    wechat.send({
                                        ToUserName: result.FromUserName,
                                        FromUserName: result.ToUserName,
                                        CreateTime: new Date().getTime() / 1000,
                                        MsgType: 'text',
                                        Content: '暂未开启，敬请期待'
                                    })
                                    break
                                case '12':
                                    wechat.send({
                                        ToUserName: result.FromUserName,
                                        FromUserName: result.ToUserName,
                                        CreateTime: new Date().getTime() / 1000,
                                        MsgType: 'text',
                                        Content: '您好！很高兴为您服务！您只需在公众号对话栏输入您想咨询了解的信息，就会有专业客服接入为您解答！'
                                    })
                                    break
                                case '13':
                                    wechat.send({
                                        ToUserName: result.FromUserName,
                                        FromUserName: result.ToUserName,
                                        CreateTime: new Date().getTime() / 1000,
                                        MsgType: 'text',
                                        Content: `您好！请拨打服务热线：4009202011
请拨打服务热线：4009202011`
                                    })
                                    break
                                case '14':
                                    wechat.send({
                                        ToUserName: result.FromUserName,
                                        FromUserName: result.ToUserName,
                                        CreateTime: new Date().getTime() / 1000,
                                        MsgType: 'text',
                                        Content: `该功能暂未开放.敬请期待！
请关注1月23日该功能公测时间，如符合资格的客户需使用该功能的指引，可联系相关销售工作人员咨询使用指引，谢谢！`
                                    })
                                    break
                                default:
                                    wechat.send('success')
                                    break
                            }
                        }
                        break
                    case 'text':
                        switch (result.Content) {
                            default: var date = new Date()
                            if (date.getHours() > 9 && date.getHours() < 21) {
                                wechat.send('success')
                            } else {
                                logger.debug('[' + __filename + ':' + __line + ']', '要自动回复')
                                wechat.send({
                                    ToUserName: result.FromUserName,
                                    FromUserName: result.ToUserName,
                                    CreateTime: Math.floor(date.getTime() / 1000),
                                    MsgType: 'text',
                                    Content: '非常抱歉，我们的服务时间是周一至周日，上午9:00至晚上21:00；在非服务时间内，您可以留下姓名和联系方式，我们会尽快致电给您，感谢您的配合！'
                                })
                            }
                            break
                        }
                        break
                    default:
                        wechat.send('success')
                        break
                }
            }
        })
    }
}

function getAdvLink(result, logObj) {
    return new Promise((resolve, reject) => {
        fanliTool.getAdvLink(result.Content, logObj).then(item => {
            var content = ''
            if (item.result == -1) {
                if (item.msg != '该商品不能返利' && item.msg != '不支持该链接') {
                    return
                }
                content = item.msg
            } else {
                content = `亲，` + (item.advLink.indexOf('jd') != -1 ? `请直接点击链接购买` : `请长按复制以下整段信息打开綯℡寳APP`) + `：
-------------------` + (item.title ? `
宝贝名称：` + item.title : ``) + (item.price ? `
参考价：` + item.price : ``) + (item.rate ? `
返现比例：` + item.rate + `%` : ``) + `
下单链接：` + item.advLink + (item.tpwd ? `
啕口令：` + item.tpwd : ``)
            }
            //logger.debug('[' + __filename + ':' + __line + ']', item)
            Wechat({
                AppID: 'wx226c3c9557c44304',
                AppSecret: '8bff6155d050947d06bf7802e69f4acb'
            }).messageCustomSend({
                touser: result.FromUserName,
                msgtype: 'text',
                content
            }).then(result => {
                if (result.errcode)
                    logger.error('[' + __filename + ':' + __line + ']', result)
                if (taobaoLoginResolveMng.hasResolve) {
                    taobaoLoginResolveMng.hasResolve = false
                    taobaoLoginResolveMng.resolve()
                }
                resolve()
            }, result => {
                if (result)
                    logger.error('[' + __filename + ':' + __line + ']', result)
                resolve()
            })
        }, _result => {
            logger.error('[' + __filename + ':' + __line + ']', result.Content, _result || '')
            reject()
        })
    })
}

function appendTaobaoResolvePromise(result, logObj) {
    taobaoLoginResolveMng.promise = new Promise((resolve, reject) => {
        taobaoLoginResolveMng.promise.then(() => {
            getAdvLink(result, logObj).then(() => {
                resolve()
            }, () => {
                if (!taobaoLoginResolveMng.hasResolve) {
                    taobaoLoginResolveMng.hasResolve = true
                    taobaoLoginResolveMng.resolve = resolve
                }
                appendTaobaoResolvePromise(result, logObj)
            })
        })
    })
}